<template>
  <div>
    <el-card>
      <el-row>
        <el-col>
          <el-input
            placeholder="请输入内容"
            v-model="search"
            style="width: 200px"
          >
          </el-input>

          <el-button
            type="primary"
            @click="showCateDialog()"
            style="margin-left: 5px"
            >添加分类</el-button
          >
        </el-col>
      </el-row>
    </el-card>
    <el-table
      :data="
        tableData.filter(
          (data) =>
            !search ||
            data.classificationName.toLowerCase().includes(search.toLowerCase())
        )
      "
      highlight-current-row
      v-loading="listLoading"
      style="width: 100%"
      row-key="id"
      :tree-props="{ children: 'children' }"
      border=""
    >
      <el-table-column
        prop="classificationName"
        label="分类名称"
      ></el-table-column>
      <!-- 排序 -->
  <el-table-column prop="classLevel" label="排序">
        <template scope="scope">
          <el-tag v-if="scope.row.classLevel === 1">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.classLevel === 2"
            >二级</el-tag
          >
          <el-tag type="warning" v-else-if="scope.row.classLevel === 3">三级</el-tag>
           <el-tag type="info" v-else-if="scope.row.classLevel === 4"
            >四级</el-tag
          >
            <el-tag type="danger" v-else
            >五级</el-tag
          >
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            title="确定删除吗？"
            @confirm="handleDel(scope.$index, scope.row)"
          >
            <el-button size="mini" type="danger" slot="reference"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加分类对话框 -->
    <el-dialog title="添加分类" :visible.sync="addCateDialogVisible">
      <!-- 添加分类的表单 -->
      <el-form
        :model="addCateForm"
        ref="addCateFormRef"
        :rules="addCateFormRules"
        label-width="100px"
      >
        <el-form-item label="分类名称:" prop="classificationName">
          <el-input v-model="addCateForm.classificationName"></el-input>
        </el-form-item>
        <el-form-item label="父级分类:">
          <el-cascader
            :options="tableData"
            v-model="selectedKeys"
            :props="{
              value: 'id',
              label: 'classificationName',
              children: 'children',
              checkStrictly: true,
            }"
            clearable
            @change="parentCateChanged"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCateclick">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类名称 -->
    <el-dialog
      title="编辑分类名称"
      :visible.sync="dialogFormVisible"
      width="600px"
    >
      <el-form ref="form" :model="form" :rules="addCateFormRules">
        <el-form-item
          label="分类名称"
          :label-width="formLabelWidth"
          prop="classificationName"
        >
          <el-input
            v-model="form.classificationName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addType, getType, editType, deleteType } from "../../api/type";
export default {
  data() {
    return {
      formLabelWidth: "120px",
      //搜索
      search: "",
      //子级
      parentCateList: {},
      addCateDialogVisible: false,
      // 添加分类表单数据对象
      addCateForm: {
        // 将要添加的分类名称
        classificationName: "",
        // 父级分类的id
        parentLevelId: 0,
        // 分类的等级，默认要添加的是1一级分类
        classLevel: 1,
      },
      dialogFormVisible: false,
      form: {
        classificationName: "",
        id: 0,
        newIndex: 0,
      },
      listLoading: false,
      // 表格数据
      tableData: [],
      selectedKeys: {},
      addCateFormRules: {
        classificationName: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
    };
  },

  methods: {
    parentCateChanged(values) {
      console.log(values);
      // 如果selectedKeys数组中的length大于0，证明选中的父级分类
      if (this.selectedKeys.length > 0) {
        // 父级分类的ID
        this.addCateForm.parentLevelId =
          this.selectedKeys[this.selectedKeys.length - 1];
        // 为当前分类的等级赋值
        this.addCateForm.classLevel = this.selectedKeys.length + 1;
        // eslint-disable-next-line no-useless-return
        return;
      } else {
        // 父级分类的id
        this.addCateForm.parentLevelId = 0;
        // 为当前分类的等级赋值
        this.addCateForm.classLevel = 1;
      }
    },
    //添加
    showCateDialog() {
      this.addCateDialogVisible = true;
    },
    // 提交添加分类
    addCateclick() {
      this.$refs.addCateFormRef.validate((valid) => {
        if (valid) {
          addType(this.addCateForm).then(({ data }) => {
            if (data.code == 200) {
              let obj = data.data;
              this.selectedKeys = [];
              if (obj.classLevel != 1) {
                let newArr = this.tableData;
                this.a(newArr, obj);
                this.selectedKeys = [];
              } else {
                this.tableData.push(obj);
                this.selectedKeys = [];
              }
              this.addCateDialogVisible = false;
            } else {
              this.$message.error(data.msg);
            }
            this.selectedKeys = [];
            this.addCateForm = {};
          });
        } else {
          this.$message.error("该空不能为空，请填写完毕重新提交");
        }
      });
    },
    a(arr, obj) {
      if (arr != null) {
        try {
          arr.forEach((item) => {
            if (item.id == obj.parentLevelId) {
              if (item.children == null) {
                item.children = [];
                item.children.push(obj);
              } else {
                item.children.push(obj);
              }
              throw new Error("EndIterative");
            } else {
              this.a(item.children, obj);
            }
          });
        } catch (e) {
          if (e.message != "EndIterative") throw e;
        }
      } else {
        console.log("看看就好..");
      }
    },
    handleEdit(index, row) {
      this.form.classificationName = row.classificationName;
      this.form.id = row.id;
      this.form.newIndex = index;
      this.dialogFormVisible = true;
    },
    // 修改分类名称
    confirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          editType(this.form.id, this.form).then(({ data }) => {
            this.tableData.splice(this.form.newIndex, data.data);
            this.dialogFormVisible = false;
          });
        } else {
          this.$message.error("该空不能为空，请填写完毕重新提交");
        }
      });
    },
    handleDel(index, row) {
      deleteType(row.id).then(({ data }) => {
        // this.tableData.splice(index, 1);
          location.reload();
        this.$message.success(data.msg);
      });
    },
  },
  mounted() {
    getType().then(({ data }) => {
      this.tableData = data.data;
    });
  },
};
</script>

<style>
</style>